import 'package:aweb5/Constants.dart';
import 'package:aweb5/bean/aplus/phone_code_entity.dart';
import 'package:aweb5/generated/json/member_info_entity_helper.dart';
import 'package:aweb5/generated/json/phone_code_entity_helper.dart';
import 'package:aweb5/pages/AplusHomePage.dart';
import 'package:aweb5/util/JsonUtil.dart';
import 'package:aweb5/util/toast_util.dart';
import 'package:aweb5/widgetlib/LoginFormCode.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:aweb5/util/StringUtil.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:aweb5/config/Config.dart';
import 'package:aweb5/util/HttpClient.dart';
import 'package:aweb5/bean/aplus/member_info_entity.dart';
import 'package:aweb5/util/SharedUtil.dart';
import 'package:aweb5/util/DateUtil.dart';
import 'package:aweb5/util/NaviUtil.dart';
import 'package:load/load.dart';
import 'package:aweb5/Constants.dart';
import 'package:aweb5/pages/AplusLoginWithPhone.dart';
import 'package:aweb5/pages/AplusHomePage.dart';
import 'package:aweb5/util/FileUtil.dart';
import 'package:aweb5/util/HttpUtils1.dart';
import 'package:flutter/material.dart';
import 'package:aweb5/util/fluwxUtil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:fluwx/fluwx.dart';
import 'package:load/load.dart';
import 'package:aweb5/Constants.dart';
import 'package:aweb5/bean/aplus/phone_code_entity.dart';
import 'package:aweb5/generated/json/member_info_entity_helper.dart';
import 'package:aweb5/generated/json/phone_code_entity_helper.dart';
import 'package:aweb5/pages/AplusHomePage.dart';
import 'package:aweb5/util/JsonUtil.dart';
import 'package:aweb5/widgetlib/LoginFormCode.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:aweb5/util/StringUtil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:aweb5/config/Config.dart';
import 'package:aweb5/util/HttpClient.dart';
import 'package:aweb5/bean/aplus/member_info_entity.dart';
import 'package:aweb5/util/SharedUtil.dart';
import 'package:aweb5/util/DateUtil.dart';
import 'package:aweb5/util/NaviUtil.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:aweb5/util/PermissionUtil.dart';
import 'Agreement1.dart';
import 'package:aweb5/util/DialogUtil.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'AplusRegistery.dart';
class LoginWithPhone extends StatefulWidget {
  bool show;
  LoginWithPhone(this.show);
  @override
  _LoginWithPhoneState createState() => _LoginWithPhoneState();
}

class _LoginWithPhoneState extends State<LoginWithPhone> {
  TextEditingController accountController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  bool hasSendCode = false;
  Function callBack;
  String _result = "无";
  String code = "";
  BuildContext context;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.callBack = requestCode;

    if(widget.show){
      WidgetsBinding.instance.addPostFrameCallback((Duration duration) {
        print(">>>post");

//        if(v==null){



        DialogUtil.showdialog(
            context,
            WillPopScope(child:
            Column(
              children: <Widget>[
                Text("个人信息保护指引",style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold),),
                Expanded(child: SingleChildScrollView(
                  child: Html(
                    data: """
    <!--For a much more extensive example, look at example/main.dart-->
     
    <p>1. 在浏览使用时，我们会使用您的设备标识信息用于推荐。</p>
<p>2. 我们可能会使用您的位置信息，为您推荐附近的服务，但不会收集和存储任何精确位置信息。</p>
<p>3. 您可以查看完整版<a href="https://h5.hhnry.com/agreement.html">《用户协议》</a>和<a href="https://h5.hhnry.com/agreement1.html">《隐私政策》</a>以便了解我们使用您手机信息的情况，以及对信息的保护措施。</p>
<br>
<br>
    <p>如果您同意请点击下面的按钮以接收我们的服务。</p>
     
  """,
                    //Optional parameters:
                    padding: EdgeInsets.all(8.0),
                    backgroundColor: Colors.white70,
                    defaultTextStyle: TextStyle(fontFamily: 'serif'),
                    linkStyle: const TextStyle(
                      color: Colors.redAccent,
                    ),
                    onLinkTap: (url) {
                      if(url=="https://h5.hhnry.com/agreement.html"){
                        NaviUtil.push(context, Agreement1("xiyi"));
//                      NaviUtil.push(new MaterialPageRoute(builder: (con){return
//                        Agreement1("xiyi");
//                      }));
                      }else{
                        NaviUtil.push(context, Agreement1("p"));

                      }
//                      launch(url);
                      // open url in a webview
                    },
                    onImageTap: (src) {
                      // Display the image in large form.
                    },
                    //Must have useRichText set to false for this to work.
                  ),
                ))
                ,
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    InkWell(
                      child: Center(
                        child: Center(
                          child: Text(
                            "暂不使用",
                            style: TextStyle( fontSize: 18),
                          ),
                        ),
                      ),
                      onTap: (){
                        SystemChannels.platform.invokeMethod('SystemNavigator.pop');
                      },
                    )
                    ,
                    InkWell(
                      child: Center(
                        child: Text(
                          "同意",
                          style: TextStyle(color: Color(0xffFF5B00), fontSize: 18),
                        ),
                      ),
                      onTap: () {
                        NaviUtil.pop(context);

                        setFirst();
                      },
                    )
                  ],
                )

              ],
            ), onWillPop: (){
              SystemChannels.platform.invokeMethod('SystemNavigator.pop');
            })
            ,
            450);
      });
    }





    weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is WeChatAuthResponse) {

        setState(() {
          _result =
          "state :${res.state}   code:${res.code} success:${res.isSuccessful}";

          if (res.isSuccessful == true) {

            code = res.code;

            NaviUtil.pushAndRemove(context,
                HomePage(Constants.memberInfoEntity.data.memberId.toString()));
//            requestLogin();
          }
        });
      }
    });


  }

  @override
  Widget build(BuildContext context) {
    this.context = context;
    return

         Scaffold(
          body: buildBody(context),
        )

      ;
  }

  Widget buildBody(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child: Text(""),
            flex: 6,
          ),
          Container(

            child: Image.asset(
              "assets/jjhw.png",
              height: 60,
              width: 150,
              fit: BoxFit.fill,
            ),
          ),
          Expanded(
            child: Text(""),
            flex: 2,
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 3, horizontal: 10),
            child: Text(
              "用心体验过的极好物品",
              style: TextStyle(color: Color(0xfff64269), fontSize: 12),
            ),
            decoration: BoxDecoration(
                border: Border.all(color: Color(0xfff64269)),
                borderRadius: BorderRadius.circular(5)),
          ),
          Expanded(
            child: Text(""),
            flex: 5,
          ),
          Container(
            alignment: Alignment.centerLeft,
            height: 35,
            margin: EdgeInsets.only(left: 50, right: 50),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5),
                color: Color(0xfff2f2f2)),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: TextField(
                    controller: accountController,
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                      hintText: "请输入手机号",
                      hintStyle: TextStyle(
                        color: Color(0xffa1a1a1),
                        fontSize: 12,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.only(left: 10.0,bottom: 10),

                    ),
                  ),
                ),
                InkWell(
                  child: Container(
                    width: 25,
                    height: 25,
                    padding: EdgeInsets.all(5),
                    child: Image.asset("assets/assist/guanbi1.png"),
                  ),
                  onTap: () {
                    accountController.clear();

                  },
                )
              ],
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Container(
              alignment: Alignment.centerLeft,
              height: 35,
              margin: EdgeInsets.only(left: 50, right: 50),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: Color(0xfff2f2f2)),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                      child: TextField(

                    controller: passwordController,
                    obscureText: false,
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                        hintText: "请输入验证码",
                        hintStyle: TextStyle(
                          color: Color(0xffa1a1a1),
                          fontSize: 12,

                        ),

                        border: InputBorder.none,
                        contentPadding: EdgeInsets.only(left: 10,bottom: 10)),
                  )),
                  InkWell(
                    child: Container(
                      width: 25,
                      height: 25,
                      padding: EdgeInsets.all(5),
                      child: Image.asset("assets/assist/guanbi1.png"),
                    ),
                    onTap: () {
                       passwordController.clear();
                    },
                  ),
                  Container(
                    alignment: Alignment.center,
                    width: 100,
                    height: 35,
                    child: LoginFormCode(
                      textEditingController: accountController,
                      onTapCallback: callBack,
                    ),
                  )
                ],
              )),

          GestureDetector(
            child: Container(
              margin: EdgeInsets.only(left: 50, right: 50, top: 30),
              height: 35,
              decoration: BoxDecoration(
                  color: Color(0xfff64269),
                  borderRadius: BorderRadius.circular(5)),
              child: Center(
                child: Text(
                  "登录",
                  style: TextStyle(fontSize: 18, color: Colors.white),
                ),
              ),
            ),
            onTap: () {
              if (!StringUtil.isPhone(accountController.text)) {
                Fluttertoast.showToast(msg: "请输入正确的手机号");
                return;
              }
              if (passwordController.text.isEmpty) {
                Fluttertoast.showToast(msg: "请输入验证码");
                return;
              }
              if ((!hasSendCode) && passwordController.text.isNotEmpty) {
                Fluttertoast.showToast(msg: "请点击发送验证码");
                return;
              }
              requestLogin();
//              request();
            },
          ),


          GestureDetector(
            child: Container(
              margin: EdgeInsets.only(left: 50, right: 50, top: 30),
              height: 35,
              decoration: BoxDecoration(
                  color: Color(0xffe97256),
                  borderRadius: BorderRadius.circular(5)),
              child: Center(
                child: Text(
                  "注册",
                  style: TextStyle(fontSize: 18, color: Colors.white),
                ),
              ),
            ),
            onTap: () {
//              if (!StringUtil.isPhone(accountController.text)) {
//                Fluttertoast.showToast(msg: "请输入正确的手机号");
//                return;
//              }
//              if (passwordController.text.isEmpty) {
//                Fluttertoast.showToast(msg: "请输入验证码");
//                return;
//              }
//              if ((!hasSendCode) && passwordController.text.isNotEmpty) {
//                Fluttertoast.showToast(msg: "请点击发送验证码");
//                return;
//              }
//              requestLogin();
//              request();
            NaviUtil.push(context, AplusRegistery());
            },
          ),
          Expanded(
            child: Text(""),
            flex: 10,
          ),
        ],
      ),
    );
  }

  void goWechatAuth() async{

    sendWeChatAuth(
        scope: "snsapi_userinfo",
        state: "wechat_sdk_demo_test")
        .then((data) {
//                        Fluttertoast.showToast(msg: data.toString());
    });

  }

  setFirst()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool("first", false);
  }

  void requestCode() async {
    hasSendCode = true;
    try {
      Map<String, dynamic> map = Map<String, dynamic>();
      map["mobile"] = accountController.text;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'member/login/sendSms',
          data: map);

      PhoneCodeEntity loginEntity = new PhoneCodeEntity();

      loginEntity = phoneCodeEntityFromJson(loginEntity, map1);

      if (loginEntity.code == null) {
//        Fluttertoast.showToast(msg: "null");
        return;
      }
      if (loginEntity.code == 200) {}
    } catch (e) {
      print(e.toString());
    }
  }

  void requestLogin() async {

    DialogUtil.showloadingdialog(context);
    try {
      Map<String, dynamic> map = Map<String, dynamic>();
      map["mobile"] = accountController.text;
      map["smscode"] = passwordController.text;

      Map<String, dynamic> map1 = await HttpClient.requestLogin(
          Config.requestApi + 'member/login/index',
          data: map);

      MemberInfoEntity memberInfoEntity = new MemberInfoEntity();
      memberInfoEntity = memberInfoEntityFromJson(memberInfoEntity, map1);
      DialogUtil.pop(context);
      if (memberInfoEntity.code == null) {
        return;
      }

      if (memberInfoEntity.code == 200) {

//        Fluttertoast.showToast(msg: "${memberInfoEntity.data.memberId}");
        SharedUtil.addStr(Constants.MEMBER_INFO, JsonUtil.map2json(map1));
        SharedUtil.addStr(Constants.LAST_LOGIN_TIME, DateTime.now().toString());
        Constants.memberInfoEntity = memberInfoEntity;

        Constants.TempMemberId = memberInfoEntity.data.memberId.toString();
        if(memberInfoEntity.data.isAppWechat==0){
          goWechatAuth();
        }else{
          NaviUtil.pushAndRemove(context,
              HomePage(Constants.memberInfoEntity.data.memberId.toString()));
        }

      }
    } catch (e) {
      DialogUtil.pop(context);
      print(e.toString());
    } finally {

      print(">>>>>finally111111");
    }
  }
}
